<template>
  <div>
    <el-container>
      <el-header height="90px">
        <div style="height:20px; font-size: 15px;background-color: rgba(205,205,205,0.2)">
          <div style="float: left; margin-left: 20px">
            <div>系统模块 > 角色管理</div>
          </div>
        </div>
        <div style="height: 60px;margin-top: 10px;min-height: 60px">
          <el-form ref="selectRole" :model="selectRole" :inline="true" label-width="75px">
            <el-col :span="7">
              <el-form-item label="角色名" prop="roleName">
                <el-input size="mini" v-model="selectRole.roleName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="角色编码" prop="roleCode">
                <el-input size="mini" v-model="selectRole.roleCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" size="mini" @click="getRoleList()">确定</el-button>
              <el-button size="mini" @click="toRestFild('selectRole')">重置</el-button>
            </el-col>


          </el-form>
        </div>
      </el-header>
      <el-main>
        <div style="float: left">
          <el-button @click="addRole()" type="danger" size="mini">添加</el-button>
        </div>
        <el-table
          :data="tableData"
          height="350"
          style="width: 100%;">
          <el-table-column
            label="角色名"
            align="center"
            width="180"
            prop="roleName">
          </el-table-column>
          <el-table-column
            label="角色编码"
            width="180"
            align="center"
            prop="roleCode">
          </el-table-column>
          <el-table-column
            label="创建时间"
            width="180"
            align="center"
            prop="createTime">
          </el-table-column>
          <el-table-column
            label="描述"
            width="180"
            align="center"
            prop="description">
          </el-table-column>
          <el-table-column label="操作"
                           align="center"
          >
            <template slot-scope="scope">
              <el-button @click.native.prevent="editRole(scope)"
                         type="text"
              >编辑
              </el-button>
              <el-button @click.native.prevent="deleteRole(scope)"
                         type="text"
              >删除
              </el-button>

            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage1"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
        </el-pagination>
        <el-dialog
          title="编辑操作权限"
          :visible.sync="dialogVisible"
          width="50%">
          <el-transfer
            style="text-align: left"
            v-model="value"
            :titles="['未获取权限','拥有权限']"
            :props="{
            key: 'id',
            label: 'description'
          }"
            :data="authData">
          </el-transfer>
        </el-dialog>
        <el-dialog
          :before-close="handleClose"
          :title="title"
          :visible.sync="dialogVisible1"
          width="50%">
          <div>
            <el-form ref="role" :model="role" :inline="true">
              <el-form-item label="角色Id:" prop="id">
                <el-input v-model="role.id" disabled></el-input>
              </el-form-item>
              <el-form-item :rules="[{ required: true, message: '请输入角色名称', trigger: 'blur' }]" label="角色名称:"
                            prop="roleName">
                <el-input v-model="role.roleName"></el-input>
              </el-form-item>
              <el-form-item :rules="[{ required: true, message: '请输入角色编码(全英文大写)', trigger: 'blur' }]" label="角色编码:"
                            prop="roleCode">
                <el-input v-model="role.roleCode" @change="justUpChart"></el-input>
              </el-form-item>
              <el-form-item :rules="[{ required: true, message: '请输入角色描述', trigger: 'blur' }]" label="角色描述:" prop="description">
                <el-input v-model="role.description"></el-input>
              </el-form-item>
              <el-form-item label="角色权限">

                <el-button type="primary" @click="editOperAuths()">修改操作权限</el-button>
                <el-button type="success" @click="editMenuAuths()">修改菜单权限</el-button>
              </el-form-item>
            </el-form>

          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancel()">取 消</el-button>
          <el-button type="primary" @click="sureOper()">确 定</el-button>
        </span>
        </el-dialog>
        <el-dialog
          title="编辑菜单权限"
          :visible.sync="dialogVisible2"
          width="50%">
          <div>
            <el-tree
              ref="tree"
              :data="data"
              show-checkbox
              node-key="id"
              :default-checked-keys="checkedData"
              :props="defaultProps">
            </el-tree>
            <!--            :default-expanded-keys="[2, 3]"-->
          </div>
        </el-dialog>

      </el-main>
    </el-container>

  </div>
</template>

<script>
export default {
  name: "roleModule",
  data() {
    return {
      checkedData: [],
      data: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      selectRole: {
        roleName: '',
        roleCode: '',
      },
      role: {
        id: '',
        roleName: '',
        roleCode: '',
        description: '',
      },
      dialogVisible2: false,
      title: '',
      //存放当前角色获取的操作权限
      auths: [],
      dialogVisible1: false,
      total: 0,
      currentPage1: 1,
      pageSize: 10,
      dialogVisible: false,
      //存放所有操作权限
      authData: [],
      //存放操作权限获取的id
      value: [],
      tableData: [],
      //存放当前角色id
      id: '',
      //存放当前角色对应的菜单id
      menuIds: [],
    }
  },
  mounted() {
    this.getRoleList()
  },
  methods: {
    justUpChart(){
      this.role.roleCode = this.role.roleCode.replace(/[^A-Z]/g, '');
    },
    getRoleList() {
      this.$axios({
        url: '/role/getPageRole',
        method: 'get',
        params: {
          ...this.selectRole,
          pageNo: this.currentPage1,
          pageSize: this.pageSize,
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
        } else {
          this.$message.error("查询失败！请联系管理员！")
        }
      })
    },
    toRestFild(ref) {
      this.$refs[ref].resetFields()
    },
    handleCurrentChange(val) {
      this.currentPage1 = val
      this.getRoleList()
    },
    addRole() {
      this.dialogVisible1 = true
      this.title = "新增角色"
      this.value = []
      this.checkedData = []
      this.menuIds = []
      this.authData.length === 0 && this.getAuthList()
      this.data.length === 0 && this.getMenuTree()
    },
    getMenuTree() {
      this.$axios({
        url: "/menu/getMenuTree",
        method: "get",
      }).then(res => {
        this.data = res.data.data
      })
    },
    getAuthByRole() {
      if (this.id !== '') {
        this.$axios({
          url: "/role/getAuthByRole",
          method: 'get',
          params: {id: this.id}
        }).then(res => {
          if (res.data.code === 200) {
            this.auths = res.data.data
            this.value = []
            this.auths.forEach(item => {
              this.value.push(parseInt(item))
            })
            this.authData.length === 0 && this.getAuthList()
          } else {
            this.$message.error("操作失败，请联系管理员后操作！")
          }
        })
      }
    },
    editOperAuths() {
      this.dialogVisible = true
    },
    getAuthList() {
      this.$axios({
        url: '/auth/getAuthList',
        method: 'get'
      }).then(res => {
        if (res.data.code === 200) {
          this.authData = res.data.data
        } else {
          this.$message.error("请联系管理员！")
        }
      })
    },
    editRole(scope) {
      this.dialogVisible1 = true
      this.title = '修改角色'
      let id = scope.row.id
      this.id = id
      let roleName = scope.row.roleName
      let roleCode = scope.row.roleCode
      let description = scope.row.description
      this.$nextTick(() => {
        this.role = JSON.parse(JSON.stringify({
          id: id,
          roleName: roleName,
          roleCode: roleCode,
          description: description
        }))
      })
      this.getAuthByRole()
      this.getMenuByRole()
    },
    sureOper() {
      let list = this.value
      let authStr = list.join(",")
      let url = ''
      let menuStr = ''
      if (this.$refs.tree) {
        var data1 = this.$refs.tree.getCheckedKeys();
        var data2 = this.$refs.tree.getHalfCheckedKeys()
        data1.push(...data2)
        menuStr = data1.join(",")
      } else {
        menuStr = this.checkedData.join(",")
      }
      url = this.title === '修改角色' ? '/role/updateRole' : '/role/addRole'
      this.$refs["role"].validate((res)=> {
        if (res){
          this.$axios({
            url: url,
            method: "post",
            data: {
              id: this.role.id,
              roleName: this.role.roleName,
              roleCode: this.role.roleCode,
              description: this.role.description,
              authStr: authStr,
              menuStr: menuStr,
            }
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success("操作成功！")
              this.toRestFild('role')
              this.dialogVisible1 = false
              this.getRoleList()
              this.checkedData = []
              if (this.$refs.tree) {
                this.$refs.tree.setCheckedNodes([])
              }
            } else {
              this.$message.error("操作失败，请联系管理员！")
            }
          })
        }
        }
      )

    },
    //通过角色获取到菜单
    getMenuByRole() {
      this.$axios({
        url: '/role/getMenuByRole',
        method: 'get',
        params: {
          id: this.id
        }
      }).then(res => {
        this.checkedData = []
        this.menuIds = res.data.data
        this.data.length === 0 && this.getMenuTree()
      })
    },
    //点击修改菜单权限
    editMenuAuths() {
      this.dialogVisible2 = true
      this.$nextTick(() => {
        this.menuIds.forEach(item => {
          if (!this.$refs.tree.getNode(parseInt(item)).childNodes || !this.$refs.tree.getNode(parseInt(item)).childNodes.length) {
            this.checkedData.push(parseInt(item))
          }
        })
      })
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.checkedData)
      })
    },
    cancel() {
      this.toRestFild('role')
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.checkedData = []
      this.dialogVisible1 = false
    },
    //关闭前操作
    handleClose() {
      this.toRestFild('role')
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.checkedData = []
      this.dialogVisible1 = false
    },
    //删除
    deleteRole(scope) {
      this.$confirm('确认删除？')
        .then(_ => {
          let id = scope.row.id
          this.$axios({
            url: '/role/deleteRole',
            method: 'delete',
            params: {
              id: id
            }
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success("删除成功！")
              this.getRoleList()
            } else {
              this.$message.error("删除失败！")
            }
          })
        })
        .catch(_ => {
        });
    },
  }
}
</script>

<style scoped>

</style>
